package com.moba.controller;

import com.alibaba.fastjson.JSONObject;
import com.moba.emums.CodeType;
import com.moba.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author 刘佳
 * @date: 2018/08/15
 */
@RestController
@RequestMapping("/common/uploader")
@Api(tags = {"文件上传"})
public class UploaderController extends BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping(value = "")
    @ApiOperation(value = "文件上传")
    public Object uploader(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        ServletOutputStream out = response.getOutputStream();
        HttpSession session = request.getSession();

        // 文件保存目录路径
        String savePath =
                session.getServletContext().getRealPath(String.valueOf(File.separatorChar))
                        + File.separatorChar
                        + "files"
                        + String.valueOf(File.separatorChar);
        // 文件保存目录URL
        String saveUrl = "files" + String.valueOf(File.separatorChar);

        // 最大文件大小5M
        long maxSize = 5120000;
        response.setContentType("text/html; charset=UTF-8");

        if (!ServletFileUpload.isMultipartContent(request)) {
            return ResultUtils.error(CodeType.CODE_TYPE_100);
        }
        // 检查目录
        File uploadDir = new File(savePath);

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            return ResultUtils.error(CodeType.CODE_TYPE_100);
        }

        String type = request.getParameter("dir");
        String dirNameForm = request.getParameter("dirName");
        // 定义允许上传的文件扩展名
        String[] fileTypes = this.setFileTypes(type);
        String filetypes_string = ArrayUtils.toString(fileTypes);

        String dirName = StringUtils.join(new String[]{"user", ""}, File.separatorChar);
        if (StringUtils.isNotBlank(dirNameForm)) {
            dirName = StringUtils.join(new String[]{dirNameForm, ""}, File.separatorChar);
        }

        // 创建文件夹
        savePath += dirName;
        saveUrl += dirName;
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + String.valueOf(File.separatorChar);
        saveUrl += ymd + String.valueOf(File.separatorChar);
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 设置上下方文
        CommonsMultipartResolver multipartResolver =
                new CommonsMultipartResolver(request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {

                MultipartFile file = multiRequest.getFile(iter.next());

                String fileName = file.getOriginalFilename();
                logger.info("==item.getSize():{}", file.getSize());
                // 检查文件大小
                if (file.getSize() > maxSize) {
                    return ResultUtils.error(CodeType.CODE_TYPE_100);
                }
                // 检查扩展名
                String fileExt = FilenameUtils.getExtension(fileName).toLowerCase();
                if (!Arrays.<String>asList(fileTypes).contains(fileExt)) {
                    return ResultUtils.error(CodeType.CODE_TYPE_100);
                }

                String newFileName = UUID.randomUUID().toString() + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    file.transferTo(uploadedFile);

                } catch (Exception e) {
                    return ResultUtils.error(CodeType.CODE_TYPE_100);
                }

                String ctx = super.getCtxPath(request);

                JSONObject obj = new JSONObject();
                String url =
                        StringUtils.replace(saveUrl + newFileName, String.valueOf(File.separatorChar), "/");
                obj.put("url", url);
                obj.put("newFileName", newFileName);
                obj.put("fileName", fileName);
                return ResultUtils.success(obj);
            }
        }
        return ResultUtils.error(CodeType.CODE_TYPE_100);
    }


    private String[] setFileTypes(String type) {
        // 图片image flash文件 flash 音频 media 文件file
        String[] fileTypes = null;
        if (StringUtils.isBlank(type)) {
            type = "image";
        }
        if ("image".equalsIgnoreCase(type)) {
            fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
        }
        if ("flash".equalsIgnoreCase(type)) {
            fileTypes = new String[]{"swf", "fla"};
        }
        if ("media".equalsIgnoreCase(type)) {
            fileTypes = new String[]{"mp3", "wma"};
        }
        // fileTypes = new String[] { "doc", "docx", "xlsx", "xls", "txt" };
        if ("file".equalsIgnoreCase(type)) {
            fileTypes =
                    new String[]{
                            "7z", "aiff", "asf", "avi", "bmp", "csv", "doc", "docx", "fla", "flv", "gif", "gz",
                            "gzip", "jpeg", "jpg", "mid", "mov", "mp3", "mp4", "mpc", "mpeg", "mpg", "ods", "odt",
                            "pdf", "png", "ppt", "pptx", "pxd", "qt", "ram", "rar", "rm", "rmi", "rmvb", "rtf",
                            "sdc", "sitd", "swf", "sxc", "sxw", "tar", "tgz", "tif", "tiff", "txt", "vsd", "wav",
                            "wma", "wmv", "xls", "xlsx", "xml", "zip"
                    };
        }
        return fileTypes;
    }
}
